package com.microframework.base.core.util;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 异常工具类
 */
public class ExceptionUtil {
    
    /**
     * 获取异常信息
     * 
     * @param e 异常
     * @return 异常信息
     */
    public static String getExceptionMessage(Throwable e) {
        if (e == null) {
            return "";
        }
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw, true));
        return sw.toString();
    }

    /**
     * 获取异常的根本原因
     * 
     * @param e 异常
     * @return 根本原因
     */
    public static Throwable getRootCause(Throwable e) {
        Throwable rootCause = e;
        while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
            rootCause = rootCause.getCause();
        }
        return rootCause;
    }

    /**
     * 获取异常的根本原因消息
     * 
     * @param e 异常
     * @return 根本原因消息
     */
    public static String getRootCauseMessage(Throwable e) {
        Throwable root = getRootCause(e);
        return (root == null) ? "" : root.getMessage();
    }
} 